//
// Created by 29019 on 2019/5/4.
//

#include "rtp.h"

int Pack264(unsigned char *frame,int size, unsigned char *outbuf[]){
    if((nullptr == frame) || (nullptr == outbuf)){
        return 0;
    }
    if((frame[0] != 0x00)&&(frame[1] != 0x00)&&(frame[2] != 0x00) && (frame[3] != 0x01)){
        return -1;
    }
    int packCnt = (size - 4) /MAX_RTP_LEN;
    if(packCnt % MAX_RTP_LEN != 0){
        packCnt +=1;
    }
    outbuf = (unsigned char **)malloc(sizeof(unsigned char *)*packCnt);
    RtspInterleavedFrameHeader rtspInterleavedFrameHeader;
    rtspInterleavedFrameHeader.magic = 0x24;
    rtspInterleavedFrameHeader.channel = 0;

    CRtpHeader header;
    header.version = 2;
    header.cc = 0;
    header.m = 0;
    header.p = 0;
    header.pt = 96;
    header.seq = 1;
    header.ts = 0x1234;
    header.x = 0;
    header.ssrc = 0x1235;

    CH264NalUnit nalUnit;
    nalUnit.Identifier.FUType = 28;
    nalUnit.Identifier.NRI = 2;
    nalUnit.Identifier.F = 0;
    nalUnit.Header.NALUnitType = 1; // idr picture
    nalUnit.Header.Forbid = 0;

    for(int i = 0;i < packCnt;i++) {
        if(i == packCnt - 1){
            nalUnit.Header.End = 1;
            nalUnit.Header.Start = 0;
            rtspInterleavedFrameHeader.length = MAX_RTP_LEN + sizeof(CH264NalUnit) + sizeof(CRtpHeader);

        }else if(i == 0){
            char *rtpBuf = (char *)malloc(MAX_RTP_LEN + sizeof(CH264NalUnit) + sizeof(CRtpHeader) +
                                          sizeof(RtspInterleavedFrameHeader));
            rtspInterleavedFrameHeader.length = MAX_RTP_LEN + sizeof(CH264NalUnit) + sizeof(CRtpHeader);
            nalUnit.Header.End = 0;
            nalUnit.Header.Start = 1;
        }else{
            nalUnit.Header.End = 0;
            nalUnit.Header.Start = 0;
            rtspInterleavedFrameHeader.length = MAX_RTP_LEN + sizeof(CH264NalUnit) + sizeof(CRtpHeader);

        }
    }
    return packCnt;
}